#ifndef SLIP_H
#define SLIP_H

#include <Arduino.h>
#include <vector>

class SlipStream {
public:
    static const uint8_t END = 0xC0;
    static const uint8_t ESC = 0xDB;
    static const uint8_t ESC_END = 0xDC;
    static const uint8_t ESC_ESC = 0xDD;

    SlipStream(HardwareSerial &serial, size_t maxFrameSize = 1024);

    void send(const uint8_t *payload, size_t length);
    int poll();
    int feed(const uint8_t *data, size_t length);
    bool has_frame() const;
    int dropped_frames() const;
    void flush_rx();
    int recv(uint8_t *outBuffer, size_t &outLength);

private:
    HardwareSerial &serial;
    size_t maxFrameSize;
    std::vector<uint8_t> rxBuffer;
    std::vector<std::vector<uint8_t>> rxFrames;
    bool escapePending;
    int droppedFramesCount;

    int processByte(uint8_t byte);
    int appendByte(uint8_t byte);
    int finishFrame();
    int dropFrame();
};

#endif // SLIP_H
